package com.xzj.admin.resource.analysis.handle.redis;

import com.xzj.admin.analysis.base.common.redis.ICustomRedisHandle;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @program: xzj-admin
 * @ClassName: CustomRedisHandle
 * @description: 自定义redis处理类
 * @author: XiaZunJun
 * @create: 2024-11-18 17:37
 */
@Component
public class CustomRedisHandle<T> implements ICustomRedisHandle<T> {

    @Resource
    private RedisTemplate<String,T> redisTemplate;

    @Override
    public <T> void setCacheMapValue(String key, String hKey, T value) {
        redisTemplate.opsForHash().put(key,hKey,value);
    }

    @Override
    public <T> T getCacheMapValue(String key, String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    @Override
    public void deleteHashObject(String key, String field) {
        redisTemplate.opsForHash().delete(key, field);
    }

    @Override
    public <T> void setCacheObject(String key, T value) {
        ValueOperations<String, T> stringTValueOperations = (ValueOperations<String, T>) redisTemplate.opsForValue();
        stringTValueOperations.set(key, value);
    }

    @Override
    public <T> T getCacheObject(String key) {
        ValueOperations<String, T> stringTValueOperations = (ValueOperations<String, T>) redisTemplate.opsForValue();
        return stringTValueOperations.get(key);
    }

    @Override
    public <T> Map<String, T> getCacheMap(String key) {
        HashOperations<String, String, T> operations = redisTemplate.opsForHash();
        return operations.entries(key);
    }

    @Override
    public boolean deleteObject(String key) {
        return Boolean.TRUE.equals(redisTemplate.delete(key));
    }

    @Override
    public <T> List<T> getCacheList(String key) {
        ListOperations<String, T> stringTListOperations = (ListOperations<String, T>) redisTemplate.opsForList();
        return stringTListOperations.range(key, 0L, -1L);
    }

    @Override
    public <T> long setCacheList(String key, List<T> dataList) {
        ListOperations<String, T> stringTListOperations = (ListOperations<String, T>) redisTemplate.opsForList();
        Long count = stringTListOperations.rightPushAll(key, dataList);
        return count == null ? 0L : count;
    }
}
